<?php
/**
 * This file is part of DomSql.
 * 
 * DomSql is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * DomSql is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with DomSql.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @link http://inditel.ee/
 * @copyright 2007-2009 Inditel Meedia OÜ
 * @author Oliver Leisalu <oliver@inditel.ee>
 */

/**
* @package DomSql
*/  
class DomSqlUnionQuery {
	
	private $queries = array();
	private $nrOfFields = 0;
	
	private $countFoundRows;
	private $orderBy;
	private $limit;
	
	public function __construct() {
	
	}
	
	public static function c() {
		return new DomSqlUnionQuery();
	}
	
	public function get( $alias ) {
		return $this->queries[$alias];
	}
	
	public function add( DomSqlQuery $query, $alias = NULL ) {
		if( $alias === NULL )
			$alias = count($this->queries);
		
		if( count($this->queries) == 0 )
			$query->countFoundRows( $this->countFoundRows );
		else
			$query->countFoundRows( false );
		
		$this->queries[$alias] = $query;
		
		return $this;
	}
	
	public function getQueries() {
		return $this->queries;
	}
	
	public function countFoundRows( $value = true ) {
		$this->countFoundRows = (boolean)$value;
		foreach( $this->queries as $q)
			$q->countFoundRows( $this->countFoundRows );
			break;
		return $this;
	}
	
	public function orderBy( $orderBy ) {
		$this->orderBy = $orderBy;
		return $this;
	}
	
	public function limit( $limit ) {
		$this->limit = $limit;
		return $this;
	}
	
	public function toString() {
		
		$queryString = '';
		foreach( $this->queries as $query ) {
			if( $queryString === '' )
				$queryString .= '(';
			else
				$queryString .= ') UNION (';
			
			$queryString .= $query->toString();
		}
		
		if( $this->orderBy !== NULL )
			$queryString .= ' ORDER BY '.$this->orderBy;
			
		if( $this->limit !== NULL )
			$queryString .= ' LIMIT '.$this->limit;
		
		return $queryString . ')';
	}
	
	public function getIterator() {
		return new DomSqlQueryIterator( $this );
	}
	
	public function execute() {
		if( $this->limit === 1) {
			$i = $this->getIterator();
			$i->rewind();
			return $i->current();
		} else {
			return $this->getIterator();
		}
	}
	
	/**
	* Alias for execute.
	* @deprecated
	*/
	public function commit() {
		return $this->execute();
	}
	
	public function __clone() {
		foreach( $this->queries as $i => $query )
			$this->queries[$i] = clone $query;
	}

}
?>